﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TestDelayedService
{
    public abstract class LongTaskBase : IDisposable
    {
        //bool m_isRunning = false;
        CancellationTokenSource tokenSource = null;

        internal CancellationTokenSource CancellationToken
        {
            get { return tokenSource; }
            set { tokenSource = value; }
        }

        public LongTaskBase()
        {

        }

        public abstract void Init();
        public abstract void Dispose();

        internal void InitializeLongTask()
        {
            //m_isRunning = true;

            //while (m_isRunning)
            //{
            //    Console.WriteLine("aaa");
            //}

            while (!tokenSource.Token.IsCancellationRequested)
            {
                tokenSource.Token.ThrowIfCancellationRequested();
            }
        }

        //internal void DisposeLongTask()
        //{
        //    m_isRunning = false;
        //}
    }

    public class FakeWorker : LongTaskBase
    {
        AutoResetEvent autoEvent = null;
        Timer m_timer = null;

        public FakeWorker()
        {
            
        }

        public override void Init()
        {
            autoEvent = new AutoResetEvent(false);

            StatusChecker statusChecker = new StatusChecker(10);

            m_timer = new Timer(statusChecker.CheckStatus, autoEvent, 2000, 250);

            base.InitializeLongTask();
        }

        public override void Dispose()
        {
            if (m_timer != null)
            {
                m_timer.Dispose();
            }

            //base.DisposeLongTask();
        }
    }

    public class StatusChecker
    {
        private int invokeCount;
        private int maxCount;

        public StatusChecker(int count)
        {
            invokeCount = 0;
            maxCount = count;
        }

        // This method is called by the timer delegate.
        public void CheckStatus(Object stateInfo)
        {
            AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
            Console.WriteLine("{0} Checking status {1,2}.", DateTime.Now.ToString("h:mm:ss.fff"), (++invokeCount).ToString());

            //if (invokeCount == maxCount)
            //{
            //    // Reset the counter and signal the waiting thread.
            //    invokeCount = 0;
            //    autoEvent.Set();
            //}
        }
    }
}
